package com.protocols;

import java.io.Serializable;
import java.nio.ByteBuffer;

public class BCDNumber implements Serializable{
	public String Value;
	private String Filler;
	
	public BCDNumber() {
		Value = "";
		Filler = "F";
	}

	public BCDNumber(String filler) {
		Value = "";
		Filler = filler;
	}

	
	public BCDNumber(String val,String filler) {
		Value = val;
		Filler = filler;
	}
	
	public BCDNumber(byte [] val, Boolean odd,String filler) {		
		Filler = filler;
		setValue( val,  odd);
	}
	

	public String getValue() {
		return Value;
	}
	public void setValue(String value) {
		
		Value = value;
	}
	
	public void setValue(byte [] val, Boolean odd) { //Convert to String, decide odd even by given instruction
		int i=0;
		String value="";
		while (i<val.length){
			value+=(val[i] & 0b00001111);
			value+=(val[i] & 0b11110000)>>4;
			i++;			
		}
		
		value=value.replace('a', '+');
		value=value.replace('b', '*');
		value=value.replace('c', '#');
		
		Value = odd ? value.substring(0, value.length()-1):value;
	}
	
	public void setValue(byte [] val, String filler) {	// Decide odd/even by the filler
		int i=0;
		String value="";
		while (i<val.length){
			value+=(val[i] & 0b00001111);
			value+=(val[i] & 0b11110000)>>4;
			i++;			
		}
		
		value=value.replace('a', '+');
		value=value.replace('b', '*');
		value=value.replace('c', '#');
		Value = value.substring(value.length()-1).equalsIgnoreCase(filler)?Value.substring(0,value.length()-2):Value;
	}
	

	public byte [] getByteArray(){
		String val= Value.length()%2==0?Value:(Value+Filler);
		val=val.replace('+', 'a');
		val=val.replace('*', 'b');
		val=val.replace('#', 'c');
		
		byte finalbytes[] = new byte [val.length()/2];
		int i=0;
		while (val.length()>0){
			String digit1=val.substring(0, 1);			
			val=val.substring(1);
			String digit2=val.substring(0, 1);			
			val=val.substring(1);
			 
			int intValue = Integer.parseInt(digit2+digit1, 16); 
			finalbytes[i]=(byte)intValue;
			i++;			
		}
		return finalbytes;
	}
	

	public int getLength(){
		return getByteArray().length;
	}
}
